
<template>
	<!-- <view class="containerbox bgc-white" style="background: linear-gradient(180deg,#c4f2e7,#f5f8e5,#f1f1f1)"> -->
	<view class="containerbox bgc-white">
		<uv-navbar leftText="AI 文章" auto-back placeholder bg-color="transparent"/>
		
		<scroll-view scroll-y class="containerbox pt-20" style="font-size: 36rpx">
			<view class="relative transition-filter px-30" :class="{ 'filter-5': socketStatus }" style="line-height: 55rpx">
				<view class="rich-text-view flex flex-wrap" style="padding: 0 17rpx">
					<template :key="item.id" v-for="item, index in articlelist">
						<text
							style="margin-right: 5px"
							v-if="item.text !== 'line-feed'"
							:style="item.sign ? 'color: #1abc9c' : ''" 
						>
							{{ item.text }}
						</text>
						
						<view v-else style="height: 50rpx;width: 100%" />
					</template>
					
					<view class="h-70 flex items-center" v-if="socketStatus">
						<text class="rich-text-view-cursor-blinks" />
					</view>
					<view id="scroll-into-view" />
				</view>
			</view>
		</scroll-view>
		
		<view class="bottombox justify-between flex items-center text-48">
			<view class="btn bgc-primary2" @tap="gotask">开始阅读学习</view>
		</view>
		
		
		<view class="flex w-full items-center justify-center h-full" style="top: 0;left: 0;position: fixed" v-if="socketStatus" @tap="gotask">
			<view class="dot-stretching" />
		</view>
		
		
		<!-- #ifndef MP-WEIXIN -->
		<view
			:data="{
				url: `wss://www.crazytraining.cn/hunyuan?token=${user.token}`,
				payload: {
					type: 'chat',
					payload: {
						type: 1,
						learnId: 0,
						sourceType: 3,
						userId: user.userInfo?.id,
						words: requestQuery.words,
						courseId: requestQuery.thesaurusId
					}
				}
			}" 
			
			:change:data="cusomstSocketJs.connectWs" 
		/>
		<!-- #endif -->
	</view>
</template>


<script module="cusomstSocketJs" lang="renderjs">
	let ws = null;
	let timer = null;
	export default {  
		data() {
			return {
				list: []
			};
		},
		
		destroyed() {  
			this.closeWs()  
		},  
		
		methods: {  
			closeWs() {  
				ws.close();
				ws = null; 
			},  
			
			connectWs({ url, payload }) {  
				ws && this.closeWs();
				ws = new WebSocket(url);  
				
				ws.onopen = ()  => {  
					ws.send(JSON.stringify(payload));
				};  
			
				ws.onmessage = result => {  
					const id = Math.random().toString().slice(2, 8);
					const data = JSON.parse(result.data);
					const query = { id };
					if (data.message === 'success') {
						query.text = data.data?.trim?.('\n')?.trim?.('\r\n')?.replace?.('.",', '.')?.replace?.(' "', '')?.replace?.('"', '')?.replace?.('\\', '');
						this.$ownerInstance.callMethod('onSocketMessage', query);
						this.list.push(query);
					};
					
					if (data.data?.id) {
						query.articleId = data.data?.id;
						this.$ownerInstance.callMethod('onSocketMessage', query);
						this.closeWs();
					};
					
					if (data.error === 500) {
						clearTimeout(timer);
						timer = null;
						this.$ownerInstance.callMethod('onSocketFail', '解析内容失败 请重新生成');
						this.closeWs();
					};
				}; 
				
				
				timer = setTimeout(() => {
					if (this.list.length) {
						clearTimeout(timer);
						timer = null;
						return;
					};
					
					this.$ownerInstance.callMethod('onSocketFail', '当前生成人数较多 请重新生成');
					this.closeWs();
				}, 20000);
			}  
		}  
	}  
</script>

<script>
	
	import { ref, watch, onBeforeUnmount } from 'vue';
	import useSocket from '@/pages/course/aireading/hook/useSocket';
	import { getExerDetail_api, postStartExer_api } from '@/common/apis/course';
	
	let timer = null;
	export default {
		data() {
			return {
				keylist: [],
				articleId: 0,
				keystring: '',
				timerIndex: 0,
				articlelist: [],
				socketStatus: true,
				user: uni.$store().user,
				requestQuery: uni.getStorageSync('aireading-word-next-page-request-query'),
			}
		},
		
		onShow() {
			// #ifdef MP-WEIXIN
			/** WebSocket */
			useSocket({
				onSocketMessage: this.onSocketMessage,
				payload: {
					type: 1,
					learnId: 0,
					sourceType: 3,
					userId: this.user.userInfo?.id,
					words: this.requestQuery.words,
					courseId: this.requestQuery.thesaurusId
				}
			});
			
			
			timer = setTimeout(() => {
				if (this.articlelist.length) {
					clearTimeout(timer);
					timer = null;
					return;
				};
				
				this.onSocketFail('当前生成人数较多 请重新生成');
				unmount();
			}, 20000);
			// #endif
		},
		
		methods: {
			onWxCloseSocket() {
				clearTimeout(timer);
				timer = null;
				
				uni.closeSocket({
					fail: () => {}
				});
			},
			
			onSocketFail(content) {
				uni.$fui.modal({
					content,
					showCancel: false,
					confirmColor: '#1abc9c',
					success: uni.navigateBack
				});
			},
			
			onSocketMessage(data) {
				switch(true) {
					case data.error === 500: {
						clearTimeout(timer);
						timer = null;
						this.onSocketFail('解析内容失败 请重新生成');
						break;
					}
					
					case !!data.articleId: {
						this.articleId = data.articleId;
						setTimeout(() => {
							this.articlelist.splice(this.articlelist.length - 1, 1);
							this.socketStatus = false;
							
						}, this.timerIndex * 50);
						break;
					}
					
					case data.text === 'english' || this.keylist.length && this.keylist.length < 2: {
						this.keylist.push(data.text);
						break;
					}
					
					case this.keylist.length === 2: {
						this.keystring = this.keylist.join('');
						this.keylist = [];
						break;
					}
					
					case this.keystring === 'english_' && !!data.text: {
						if (data.text === '_') {
							this.keystring = '';
							setTimeout(() => {
								this.articlelist.push({ text: 'line-feed' });
								
							}, this.timerIndex * 50);
							return;
						};
						
						++this.timerIndex;
						data.sign = this.requestQuery.words.includes(data.text.trim());
						setTimeout(() => {
							this.articlelist.push(data);
							
						}, this.timerIndex * 50);
						break;
					}
				};
			},
			
			async gotask() {
				if (this.socketStatus) {
					uni.$fui.toast('文章正在生成中...');
					return;
				};
				
				await postStartExer_api({ articleId: this.articleId, exerciseId: this.requestQuery.exerciseId });
				uni.redirectTo({ url: `/pages/course/aireading/answer?exerciseId=${this.requestQuery.exerciseId}&articleId=${this.articleId}` });
			}
		}
	}
</script>


<style lang="scss" scoped>
.filter-5{filter: blur(6rpx)}
.bottombox{padding: 20rpx 32rpx 24rpx}
.transition-filter{transition: filter .3s}
.btn{height: 90rpx; border-radius: 30rpx; flex: 1; text-align: center; line-height: 80rpx; color: #fff; font-size: 32rpx; display: flex; align-items: center; justify-content: center}
.btn+.btn{margin-left: 20rpx}	
.rich-text-view{width: fit-content}
.rich-text-view-cursor-blinks{display: inline-block;width: 5rpx;height: 36rpx;background-color: #00c386; animation: cursor-blinks 800ms infinite steps(1, start)}
@keyframes cursor-blinks {
	0%{opacity: 1;display: block}
	50%{opacity: 0;display: none}
	100%{opacity: 1;display: block}
}
</style>